/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DlgOrders.java
 *
 * Created on Jul 12, 2011, 11:49:33 PM
 */
package OtherForms;

import Helpers.ProcessThread;
import MyDatePicker.JCalendar;
import Persistences.*;
import Repositories.*;
import java.awt.event.InputEvent;
import java.math.BigInteger;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.concurrent.atomic.AtomicReference;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 *
 * @author letuan
 */
public class DlgSchedulingAndConfigs extends javax.swing.JFrame {

    JCalendar calendar = null;

    /** Creates new form DlgOrders */
    public DlgSchedulingAndConfigs(java.awt.Frame parent, boolean modal) {
        //super(parent, modal);
        initComponents();
        LoadCalendar();
        LoadOtherConfigs();
        LoadTarget();
    }

    public void LoadOtherConfigs() {
        ArrayList<Otherconfigs> lstItem = OtherConfigsRepository.selectAll();
        if (lstItem.size() > 0) {
            txtDestroyDay.setText(String.valueOf(lstItem.get(0).getCodeexpireday()));
            txtEmailCompany.setText(lstItem.get(0).getEmailcompany());
            txtPasswordEmailCompany.setText(lstItem.get(0).getPasswordemailcompany());
        }
    }

    public void LoadTarget() {
        ArrayList<Targets> lstItem = TargetsRepository.selectByMonthAndYear(calendar.getMonthChooser().getMonth() + 1, calendar.getYearChooser().getYear());
        if (lstItem.size() > 0) {
            txtTarget.setText(String.valueOf(lstItem.get(0).getTarget()));
        }
    }

    public void LoadCalendar() {
        if (calendar == null) {
            calendar = new JCalendar(tblCalendar_Month, txtTarget);
            calendar.setCheckMode(JCalendar.eTableMode.SCHEDULING);
            pnlCalendar.add(calendar);
            MonthCalendar.TableMonthTask.disableDayNotBelongMonth(this.tblCalendar_Month, calendar.getCalendar());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        pnlCalendar = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtTarget = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtDestroyDay = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        btnSave = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        txtEmailCompany = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        txtPasswordEmailCompany = new javax.swing.JPasswordField();
        jPanel4 = new javax.swing.JPanel();
        scroll_GhiChu1 = new javax.swing.JScrollPane();
        tblCalendar_Month = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Scheduling");

        jSplitPane1.setDividerSize(2);

        jPanel1.setMinimumSize(new java.awt.Dimension(200, 137));
        jPanel1.setPreferredSize(new java.awt.Dimension(200, 467));

        pnlCalendar.setLayout(new java.awt.BorderLayout());

        jLabel1.setFont(new java.awt.Font("SansSerif", 1, 12));
        jLabel1.setForeground(new java.awt.Color(204, 0, 0));
        jLabel1.setText("   Scheduling time");
        jLabel1.setPreferredSize(new java.awt.Dimension(85, 22));

        jLabel2.setFont(new java.awt.Font("SansSerif", 1, 12));
        jLabel2.setForeground(new java.awt.Color(204, 0, 0));
        jLabel2.setText("   Target:");
        jLabel2.setPreferredSize(new java.awt.Dimension(85, 22));

        jLabel3.setText("USD");

        jLabel4.setFont(new java.awt.Font("SansSerif", 1, 12));
        jLabel4.setForeground(new java.awt.Color(204, 0, 0));
        jLabel4.setText("   Code will be destroyed in:");
        jLabel4.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        jLabel4.setPreferredSize(new java.awt.Dimension(85, 22));

        jLabel5.setText("day(s)");

        btnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/81.png"))); // NOI18N
        btnSave.setText("Update");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("SansSerif", 1, 12));
        jLabel6.setForeground(new java.awt.Color(204, 0, 0));
        jLabel6.setText("   Email Company:");
        jLabel6.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        jLabel6.setPreferredSize(new java.awt.Dimension(85, 22));

        jLabel7.setFont(new java.awt.Font("SansSerif", 1, 12));
        jLabel7.setForeground(new java.awt.Color(204, 0, 0));
        jLabel7.setText("   Password Email Company:");
        jLabel7.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        jLabel7.setPreferredSize(new java.awt.Dimension(85, 22));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtTarget, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addGap(12, 12, 12))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(txtDestroyDay, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel5)))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(pnlCalendar, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(btnSave)
                        .addGap(21, 21, 21))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtEmailCompany, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(49, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtPasswordEmailCompany, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlCalendar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtTarget, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtDestroyDay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtEmailCompany, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtPasswordEmailCompany, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnSave)
                .addContainerGap(196, Short.MAX_VALUE))
        );

        jSplitPane1.setLeftComponent(jPanel1);

        jPanel4.setPreferredSize(new java.awt.Dimension(686, 467));
        jPanel4.setLayout(new java.awt.BorderLayout());

        tblCalendar_Month.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblCalendar_Month.setFillsViewportHeight(true);
        tblCalendar_Month.setGridColor(new java.awt.Color(125, 175, 255));
        tblCalendar_Month.setPreferredSize(new java.awt.Dimension(425, 535));
        tblCalendar_Month.setRowHeight(90);
        tblCalendar_Month.setRowSelectionAllowed(false);
        tblCalendar_Month.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tblCalendar_MonthMousePressed(evt);
            }
        });
        scroll_GhiChu1.setViewportView(tblCalendar_Month);

        jPanel4.add(scroll_GhiChu1, java.awt.BorderLayout.CENTER);

        jSplitPane1.setRightComponent(jPanel4);

        getContentPane().add(jSplitPane1, java.awt.BorderLayout.CENTER);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-898)/2, (screenSize.height-595)/2, 898, 595);
    }// </editor-fold>//GEN-END:initComponents

    public boolean validateInputData(AtomicReference<Object> errText) {
        if (txtTarget.getText().equals("")) {
            errText.set("Target is empty");
            return false;
        }
        if (txtDestroyDay.getText().equals("")) {
            errText.set("Expire day is empty");
            return false;
        }
        if (txtEmailCompany.getText().equals("")) {
            errText.set("Email company is empty");
            return false;
        }
        if (txtPasswordEmailCompany.getText().equals("")) {
            errText.set("Password email company is empty");
            return false;
        }
        return true;
    }

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        // TODO add your handling code here:
        boolean updated = false;
        AtomicReference<Object> errText = new AtomicReference<Object>("");
        if (!validateInputData(errText)) {
            JOptionPane.showMessageDialog(null, errText.get(),
                    "Announcement", JOptionPane.ERROR_MESSAGE);
            return;
        }   
        // Update target
        ArrayList<Targets> lstItemTarget = TargetsRepository.selectByMonthAndYear(calendar.getMonthChooser().getMonth() + 1, calendar.getYearChooser().getY());
        Targets targetItem;
        if (lstItemTarget.size() > 0) {
            targetItem = lstItemTarget.get(0);
            targetItem.setTarget(Long.parseLong(txtTarget.getText()));
            updated = TargetsRepository.save(targetItem);
        }else{
            targetItem = new Targets();
            targetItem.setMonth(calendar.getMonthChooser().getMonth() + 1);
            targetItem.setYear(calendar.getYearChooser().getYear());
            targetItem.setTarget(Long.parseLong(txtTarget.getText()));
            updated = TargetsRepository.insert(targetItem);
        }
        
        // Update other configs
        ArrayList<Otherconfigs> lstItem = OtherConfigsRepository.selectAll();
        Otherconfigs item = null;
        if (lstItem.size() > 0) {
            item = lstItem.get(0);
            item.setCodeexpireday(Integer.parseInt(txtDestroyDay.getText()));
            item.setEmailcompany(txtEmailCompany.getText());
            item.setPasswordemailcompany(txtPasswordEmailCompany.getText());
            updated = OtherConfigsRepository.save(item);
        } else {
            item = new Otherconfigs();
            item.setCodeexpireday(Integer.parseInt(txtDestroyDay.getText()));
            item.setEmailcompany(txtEmailCompany.getText());
            item.setPasswordemailcompany(txtPasswordEmailCompany.getText());
            updated = OtherConfigsRepository.insert(item);
        }
        
        if (updated) {
            JOptionPane.showMessageDialog(null, "Item has been updated",
                    "Announcement", JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(null, "Update item fail",
                    "Announcement", JOptionPane.INFORMATION_MESSAGE);
        }
}//GEN-LAST:event_btnSaveActionPerformed

    private void tblCalendar_MonthMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblCalendar_MonthMousePressed
        // TODO add your handling code here:
        int modifiers = evt.getModifiers();
        if ((modifiers & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
            if (this.tblCalendar_Month.getSelectedRow() == -1) {
                return;
            }
            if (evt.getClickCount() == 2) {
                String date = ((JPanel) tblCalendar_Month.getValueAt(
                        tblCalendar_Month.getSelectedRow(), tblCalendar_Month.getSelectedColumn())).getName();
                DlgAddSchedule dlg = new DlgAddSchedule(null, true, new Date(date));
                dlg.show();
                //load lai
                if (dlg.isAddSuccess()) {
                    // Show loading form at here
                    Calendar cal = (Calendar) calendar.getCalendar().clone();
                    ProcessThread processDlg;
                    processDlg = new ProcessThread(tblCalendar_Month, cal, "Please wailt");
                    processDlg.setLocationRelativeTo(this);
                    processDlg.startReloadScheduling();
                }
            }
        }
}//GEN-LAST:event_tblCalendar_MonthMousePressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                DlgSchedulingAndConfigs dialog = new DlgSchedulingAndConfigs(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnSave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JPanel pnlCalendar;
    private javax.swing.JScrollPane scroll_GhiChu1;
    private javax.swing.JTable tblCalendar_Month;
    private javax.swing.JTextField txtDestroyDay;
    private javax.swing.JTextField txtEmailCompany;
    private javax.swing.JPasswordField txtPasswordEmailCompany;
    private javax.swing.JTextField txtTarget;
    // End of variables declaration//GEN-END:variables
}
